<template>
  <div class="character-auditor-select-wrap">
    <div class="role-wrap">
      <div class="bread-crumb-wrap">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item v-for="(item, index) in breadCrumbData" :key="index">
            <span :class="{'active': index + 1 === breadCrumbData.length }" class="bread-crumb-item" @click="crumbClick(index)">{{ item.roleName }}</span>
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <role-auditor-select v-if="isShowCheckAll && targetDept.length > 0" :user-list="targetDept" style="padding-left: 24px" @select="searchPick" />
      <el-checkbox v-if="isShowCheckAll && targetDept.length > 0" :value="isAllChecked" style="padding-left: 24px" @change="checkAllFun">全选</el-checkbox>
      <empty-state v-if="targetDept.length === 0" height="365px" text="暂无角色" dec="管理员还没有设置角色" />
      <template v-for="(item, index) in targetDept">
        <charater-select-item v-if="item.isRole === 1" :role-info="item" :key="index" @click="roleSelected" />
        <staff-select-item v-else :key="index" :is-active="isChecked(item.userId)" :info="item" @check="targetCheck($event, 'userId')" />
      </template>
    </div>
  </div>
</template>
<script>
import StaffSelectItem from './staffSelectItem';
import { allCharaterList } from '@/api/select';
import CharaterSelectItem from './charaterSelectItem';
import RoleAuditorSelect from './roleAuditorSelect';
import EmptyState from './emptyState';
export default {
  name: 'CharacterAuditorSelect',
  components: { StaffSelectItem, CharaterSelectItem, RoleAuditorSelect, EmptyState },
  props: {
    selectItems: {
      type: Array,
      default: () => {
        return [];
      }
    },
    selectUsers: {
      type: Array,
      default: () => {
        return [];
      }
    },
    max: {
      type: Number,
      default: 50
    }
  },
  data() {
    return {
      breadCrumbData: []
    };
  },
  computed: {
    // 判断是否全选
    isAllChecked() {
      const total = this.targetDept.length;
      let currentTime = 0; // 出现次数
      this.targetDept.forEach(item => {
        const { userId } = item;
        if (userId) {
          if (this.selectItemIds.indexOf(userId) >= 0) currentTime++;
        }
      });
      return currentTime === total;
    },
    isShowCheckAll() {
      const total = this.targetDept.length;
      let currentTime = 0;
      this.targetDept.forEach(item => {
        if (!item.isRole) currentTime++;
      });
      return currentTime === total;
    },
    targetDept() {
      const lastIndex = this.breadCrumbData.length - 1;
      const lastRole = this.breadCrumbData[lastIndex];
      if (lastRole && lastRole.children) {
        return lastRole.children;
      } else {
        return [];
      }
    },
    auditorIds() {
      const temp = this.selectUsers.map(item => item.id);
      return temp;
    },
    selectItemIds() {
      if (this.selectItems.length > 0) {
        const temp = [];
        this.selectItems.forEach(item => {
          if (item.hasOwnProperty('isDepartment') || item.hasOwnProperty('isRole')) { // 有isDepartment 证明是通过部门列表获取的值
            if (item.isDepartment) {
              temp.push(item.id);
            } else {
              temp.push(item.userId);
            }
          } else {
            temp.push(item.id);
          }
        });
        return temp;
      } else {
        return [];
      }
    }
  },
  created() {
    this.getAllCharaterList();
  },
  methods: {
    // 判断复选框是否选中
    isChecked(id) {
      return this.selectItemIds.indexOf(id) >= 0;
    },
    // 全选逻辑
    checkAllFun(val) {
      if (val) {
        const total = this.selectUsers.length + this.targetDept.length;
        if (total > this.max) {
          this.$message({
            type: 'warning',
            message: '选择超过限制'
          });
          return;
        }
      }
      this.targetDept.forEach(item => {
        const param = { item, isChecked: val };
        setTimeout(() => {
          if (val) {
            if (this.selectItemIds.indexOf(item.userId) < 0) {
              this.targetCheck(param, 'userId');
            }
          } else {
            this.targetCheck(param, 'userId');
          }
        }, 0);
      });
    },
    // 员工复选框点击
    targetCheck(data, field) {
      const isCheck = data.isChecked;
      const item = data.item;
      const tempSelectItemIds = JSON.parse(JSON.stringify(this.selectItemIds));
      const tempSelectItems = JSON.parse(JSON.stringify(this.selectItems));
      if (isCheck) {
        if (this.selectUsers.length >= this.max) {
          this.$message({
            type: 'warning',
            message: '选择超过限制'
          });
          return;
        }
        tempSelectItems.push(item);
        this.$emit('update:selectItems', tempSelectItems);
        this.addStaff(item);
      } else {
        const curIndex = tempSelectItemIds.indexOf(item[field]);
        if (curIndex >= 0) {
          tempSelectItems.splice(curIndex, 1);
          this.$emit('update:selectItems', tempSelectItems);
        }
        this.deleteStaff(item);
      }
    },
    searchPick(item) {
      if (this.auditorIds.indexOf(item.id) >= 0) {
        this.$message({
          type: 'warning',
          message: '不能重复选择'
        });
        return;
      }
      if (this.auditorIds.length >= this.max) {
        this.$message({
          type: 'warning',
          message: '选择超过限制'
        });
        return;
      }
      const tempSelectUsers = JSON.parse(JSON.stringify(this.selectUsers));
      const tempSelectItems = JSON.parse(JSON.stringify(this.selectItems));
      tempSelectUsers.push(item);
      this.$emit('update:selectUsers', tempSelectUsers);
      tempSelectItems.push(item);
      this.$emit('update:selectItems', tempSelectItems);
    },
    // 添加员工逻辑
    addStaff(item) {
      const { userId, userName, avatar, post, number } = item;
      const tempSelectUsers = JSON.parse(JSON.stringify(this.selectUsers));
      const param = {
        id: userId,
        userName,
        avatar,
        post,
        number
      };
      tempSelectUsers.push(param);
      this.$emit('update:selectUsers', tempSelectUsers);
    },
    // 删除员工
    deleteStaff(item) {
      const { userId } = item;
      const tempSelectUsers = JSON.parse(JSON.stringify(this.selectUsers));
      const selectUserIds = tempSelectUsers.map(item => item.id);
      const deleteIndex = selectUserIds.indexOf(userId);
      if (deleteIndex >= 0) {
        tempSelectUsers.splice(deleteIndex, 1);
        this.$emit('update:selectUsers', tempSelectUsers);
      }
    },
    // 获取角色数据
    getAllCharaterList() {
      allCharaterList().then(res => {
        if (res.code === 200) {
          const root = {
            roleName: '飞博共创',
            children: res.data,
            isRole: 1
          };
          this.breadCrumbData = [root];
        }
      });
    },
    // 面包屑点击
    crumbClick(index) {
      if (index === this.breadCrumbData.length - 1) return;
      this.breadCrumbData = this.breadCrumbData.slice(0, index + 1);
    },
    // 角色点击
    roleSelected(item) {
      this.breadCrumbData.push(item);
    }
  }
};
</script>
<style lang="scss" scoped>
@import url('./common.scss');
.bread-crumb-wrap {
  & ::v-deep {
    .el-breadcrumb {
      line-height: 1.5 !important;
    }
    .el-breadcrumb__item {
      float: none !important;
    }
  }
}
.role-wrap {
  align-items: center;
  height: 422px;
  @include scrollBar();
}
.bread-crumb-item {
  cursor: pointer;
  font-size: 14px;
  color: #333;
  &.active {
    cursor: not-allowed;
    color: #999
  }
}
</style>
